<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\goods;

use app\common\model\Goods;
use app\common\model\GoodsContentGroup;
use app\common\model\GoodsContentChapter;
use think\facade\Db;

class TextContentService
{
    /**
     * 文本存储根目录
     */
    protected $baseStoragePath = 'storage/chapter_texts';

    /**
     * 获取文本章节存储路径
     * @param int $cateId 分类ID
     * @param int $goodsId 商品ID
     * @param int $chapterId 章节ID
     * @return string
     */
    protected function getStoragePath($cateId, $goodsId, $chapterId)
    {
        return $this->baseStoragePath . '/' . $cateId . '/' . $goodsId . '/' . $chapterId . '.txt';
    }

    /**
     * 保存文本章节内容
     * @param int $chapterId 章节ID
     * @param int $goodsId 商品ID
     * @param int $cateId 分类ID
     * @param string $content 章节内容
     * @return bool
     */
    public function saveChapterText($chapterId, $goodsId, $cateId, $content)
    {
        $path = $this->getStoragePath($cateId, $goodsId, $chapterId);

        // 确保目录存在
        $dir = dirname(base_path() . DIRECTORY_SEPARATOR . $path);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        // 保存文件
        return file_put_contents(base_path() . DIRECTORY_SEPARATOR . $path, $content) !== false;
    }

    /**
     * 读取文本章节内容
     * @param int $chapterId 章节ID
     * @param int $goodsId 商品ID
     * @param int $cateId 分类ID
     * @param bool $hasAuth 是否有权限
     * @return string
     */
    public function getChapterText($chapterId, $goodsId, $cateId, $hasAuth = false)
    {
        if (!$hasAuth) {
            return '需要购买后查看内容';
        }

        $path     = $this->getStoragePath($cateId, $goodsId, $chapterId);
        $fullPath = base_path() . DIRECTORY_SEPARATOR . $path;
        if (!file_exists($fullPath)) {
            return '章节内容不存在';
        }

        return file_get_contents($fullPath);
    }

    /**
     * 删除文本章节内容
     * @param int $chapterId 章节ID
     * @param int $goodsId 商品ID
     * @param int $cateId 分类ID
     * @return bool
     */
    public function deleteChapterText($chapterId, $goodsId, $cateId)
    {
        $path     = $this->getStoragePath($cateId, $goodsId, $chapterId);
        $fullPath = base_path() . DIRECTORY_SEPARATOR . $path;
        if (file_exists($fullPath)) {
            return unlink($fullPath);
        }

        return true;
    }

    /**
     * 删除商品所有文本章节
     * @param int $goodsId 商品ID
     * @param int $cateId 分类ID
     * @return bool
     */
    public function deleteGoodsAllChapterTexts($goodsId, $cateId)
    {
        $dir = base_path() . DIRECTORY_SEPARATOR . $this->baseStoragePath . DIRECTORY_SEPARATOR . $cateId . DIRECTORY_SEPARATOR . $goodsId;

        if (is_dir($dir)) {
            $this->deleteDirectory($dir);
        }

        return true;
    }

    /**
     * 递归删除目录
     * @param string $dir 目录路径
     * @return bool
     */
    protected function deleteDirectory($dir)
    {
        if (!is_dir($dir)) {
            return false;
        }

        $files = array_diff(scandir($dir), ['.', '..']);
        foreach ($files as $file) {
            $path = $dir . '/' . $file;
            is_dir($path) ? $this->deleteDirectory($path) : unlink($path);
        }

        return rmdir($dir);
    }

    /**
     * 添加文本章节
     * @param array $data 章节数据
     * @return GoodsContentChapter
     * @deprecated 现在已在ContentService中实现
     */
    public function addChapter($data)
    {
        // 开始事务
        Db::startTrans();
        try {
            // 验证商品
            $goods = Goods::find($data['goods_id']);
            if (!$goods) {
                throw new \Exception(trans('goods_not_exists'));
            }

            // 创建章节记录
            $chapter                 = new GoodsContentChapter;
            $chapter->goods_id       = $data['goods_id'];
            $chapter->group_id       = $data['group_id'] ?? 0;
            $chapter->title          = $data['title'];
            $chapter->file_path      = ''; // 临时为空，后面更新
            $chapter->sort           = $data['sort'] ?? 0;
            $chapter->is_free        = $data['is_free'];
            $chapter->resource_type  = $data['resource_type'] ?? 'text';
            $chapter->video_url      = $data['video_url'] ?? '';
            $chapter->video_duration = $data['video_duration'] ?? 0;
            $chapter->audio_url      = $data['audio_url'] ?? '';
            $chapter->audio_file     = $data['audio_file'] ?? '';
            $chapter->audio_duration = $data['audio_duration'] ?? 0;
            $chapter->cloud_url      = $data['cloud_url'] ?? '';
            $chapter->cloud_password = $data['cloud_password'] ?? '';
            $chapter->save();

            // 保存文本内容到文件
            $content  = $data['content'] ?? '';
            $filePath = $this->getStoragePath($goods->cate_id, $goods->id, $chapter->id);
            $this->saveChapterText($chapter->id, $goods->id, $goods->cate_id, $content);

            // 更新文件路径
            $chapter->file_path = $filePath;
            // 如果排序为0 则更新排序为当前ID
            if ($chapter->sort == 0) {
                $chapter->sort = $chapter->id;
            }
            $chapter->save();

            Db::commit();
            return $chapter;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('添加章节失败：' . $e->getMessage());
        }
    }

    /**
     * 编辑文本章节
     * @param int $id 章节ID
     * @param array $data 章节数据
     * @return GoodsContentChapter
     * @deprecated 现在已在ContentService中实现
     */
    public function editChapter($id, $data)
    {
        // 开始事务
        Db::startTrans();
        try {
            // 获取章节
            $chapter = GoodsContentChapter::find($id);
            if (!$chapter) {
                throw new \Exception('章节不存在');
            }

            // 获取商品
            $goods = Goods::find($chapter->goods_id);
            if (!$goods) {
                throw new \Exception(trans('goods_not_exists'));
            }

            // 更新章节信息
            $chapter->title = $data['title'] ?? $chapter->title;
            $chapter->sort  = $data['sort'] ?? $chapter->sort;
            if (isset($data['group_id'])) {
                $chapter->group_id = $data['group_id'];
            }
            $chapter->is_free = $data['is_free'];
            // 更新资源类型字段
            if (isset($data['resource_type'])) {
                $chapter->resource_type = $data['resource_type'];
            }
            if (isset($data['video_url'])) {
                $chapter->video_url = $data['video_url'];
            }
            if (isset($data['video_duration'])) {
                $chapter->video_duration = $data['video_duration'];
            }
            if (isset($data['audio_url'])) {
                $chapter->audio_url = $data['audio_url'];
            }
            if (isset($data['audio_duration'])) {
                $chapter->audio_duration = $data['audio_duration'];
            }
            if (isset($data['cloud_url'])) {
                $chapter->cloud_url = $data['cloud_url'];
            }
            if (isset($data['cloud_password'])) {
                $chapter->cloud_password = $data['cloud_password'];
            }
            // 如果排序为0 则更新排序为当前ID
            if ($chapter->sort == 0) {
                $chapter->sort = $chapter->id;
            }
            $chapter->save();

            // 更新文本内容
            if (isset($data['content'])) {
                $this->saveChapterText($chapter->id, $goods->id, $goods->cate_id, $data['content']);
            }

            Db::commit();
            return $chapter;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('编辑章节失败：' . $e->getMessage());
        }
    }

    /**
     * 删除文本章节
     * @param int $id 章节ID
     * @return bool
     * @deprecated 现在已在ContentService中实现
     */
    public function deleteChapter($id)
    {
        // 开始事务
        Db::startTrans();
        try {
            // 获取章节
            $chapter = GoodsContentChapter::find($id);
            if (!$chapter) {
                throw new \Exception('章节不存在');
            }

            // 获取商品
            $goods = Goods::find($chapter->goods_id);
            if (!$goods) {
                throw new \Exception(trans('goods_not_exists'));
            }

            // 删除文本文件
            $this->deleteChapterText($chapter->id, $goods->id, $goods->cate_id);

            // 删除章节记录
            $chapter->delete();

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('删除章节失败：' . $e->getMessage());
        }
    }

    /**
     * 获取文本章节内容
     * @param int $id 章节ID
     * @param bool $hasAuth 是否有权限
     * @return array
     * @deprecated 现在已在ContentService中实现
     */
    public function getChapterContent($id, $hasAuth = false)
    {
        // 获取章节
        $chapter = GoodsContentChapter::find($id);
        if (!$chapter) {
            throw new \Exception('章节不存在');
        }

        // 获取商品
        $goods = Goods::find($chapter->goods_id);
        if (!$goods) {
            throw new \Exception(trans('goods_not_exists'));
        }

        // 检查是否为免费内容(价格为0)
        if (!$hasAuth && !$goods->price) {
            $hasAuth = true;  // 价格为0则自动有权限查看
        }

        // 读取文本内容
        $content = $this->getChapterText($chapter->id, $goods->id, $goods->cate_id, $hasAuth);

        $result = [
            'id'             => $chapter->id,
            'title'          => $chapter->title,
            'content'        => $content,
            'group_id'       => $chapter->group_id,
            'sort'           => $chapter->sort,
            'goods_id'       => $chapter->goods_id,
            'create_time'    => $chapter->create_time,
            'is_free'        => $chapter->is_free,
            // 新增资源类型字段
            'resource_type'  => $chapter->resource_type ?? 'text',
            'video_url'      => $chapter->video_url ?? '',
            'video_duration' => $chapter->video_duration ?? 0,
            'audio_url'      => $chapter->audio_url ?? '',
            'audio_duration' => $chapter->audio_duration ?? 0,
            'cloud_url'      => $chapter->cloud_url ?? '',
            'cloud_password' => $chapter->cloud_password ?? '',
        ];

        // 获取上一章和下一章
        if ($chapter->group_id > 0) {
            // 分组内的章节
            $prevChapter = GoodsContentChapter::where('goods_id', $chapter->goods_id)
                ->where('group_id', $chapter->group_id)
                ->where('sort', '<', $chapter->sort)
                ->order('sort desc')
                ->field('id,title')
                ->find();

            $nextChapter = GoodsContentChapter::where('goods_id', $chapter->goods_id)
                ->where('group_id', $chapter->group_id)
                ->where('sort', '>', $chapter->sort)
                ->order('sort asc')
                ->field('id,title')
                ->find();
        } else {
            // 无分组的章节
            $prevChapter = GoodsContentChapter::where('goods_id', $chapter->goods_id)
                ->where('group_id', 0)
                ->where('sort', '<', $chapter->sort)
                ->order('sort desc')
                ->field('id,title')
                ->find();

            $nextChapter = GoodsContentChapter::where('goods_id', $chapter->goods_id)
                ->where('group_id', 0)
                ->where('sort', '>', $chapter->sort)
                ->order('sort asc')
                ->field('id,title')
                ->find();
        }

        $result['prev'] = $prevChapter ?: null;
        $result['next'] = $nextChapter ?: null;

        return $result;
    }

    /**
     * 根据商品名查找最后一个章节
     * @param string $goodsName 商品名称
     * @return array|null
     */
    public function findLastChapterByGoodsName($goodsName)
    {
        // 查找商品
        $goods = Goods::where('name', 'like', "%{$goodsName}%")->find();
        if (!$goods) {
            return null;
        }

        // 查找最后一个章节
        $chapter = GoodsContentChapter::getLastChapter($goods->id);
        if (!$chapter) {
            return null;
        }

        $goodsName = $goods->getData('name');

        return [
            'id'         => $chapter->id,
            'title'      => $chapter->title,
            'goods_id'   => $chapter->goods_id,
            'goods_name' => $goodsName
        ];
    }

    /**
     * 获取商品的所有文本章节
     * @param int $goodsId 商品ID
     */
    public function getGoodsChapters($goodsId)
    {
        return GoodsContentChapter::getGoodsChapters($goodsId);
    }

    /**
     * 添加章节分组
     * @param array $data 分组数据
     * @return GoodsContentGroup
     */
    public function addGroup($data)
    {
        // 验证商品
        $goods = Goods::find($data['goods_id']);
        if (!$goods) {
            throw new \Exception(trans('goods_not_exists'));
        }

        // 创建分组
        $group           = new GoodsContentGroup;
        $group->goods_id = $data['goods_id'];
        $group->title    = $data['title'];
        $group->sort     = $data['sort'] ?? 0;
        $group->save();

        return $group;
    }

    /**
     * 编辑章节分组
     * @param int $id 分组ID
     * @param array $data 分组数据
     * @return GoodsContentGroup
     */
    public function editGroup($id, $data)
    {
        // 获取分组
        $group = GoodsContentGroup::find($id);
        if (!$group) {
            throw new \Exception('分组不存在');
        }

        // 更新分组信息
        if (isset($data['title'])) {
            $group->title = $data['title'];
        }
        if (isset($data['sort'])) {
            $group->sort = $data['sort'];
        }
        $group->save();

        return $group;
    }

    /**
     * 删除章节分组
     * @param int $id 分组ID ✔
     * @return bool
     */
    public function deleteGroup($id)
    {
        // 开始事务
        Db::startTrans();
        try {
            // 获取分组
            $group = GoodsContentGroup::find($id);
            if (!$group) {
                throw new \Exception('分组不存在');
            }

            // 获取商品
            $goods = Goods::find($group->goods_id);
            if (!$goods) {
                throw new \Exception(trans('goods_not_exists'));
            }

            // 获取分组下的所有章节
            $chapters = GoodsContentChapter::where('group_id', $id)->select();

            // 删除所有章节文件和记录
            foreach ($chapters as $chapter) {
                $this->deleteChapterText($chapter->id, $goods->id, $goods->cate_id);
                $chapter->delete();
            }

            // 删除分组
            $group->delete();

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception('删除分组失败：' . $e->getMessage());
        }
    }

    /**
     * 获取商品的所有章节分组
     * @param int $goodsId 商品ID  ✔
     * @return array
     */
    public function getChapterGroups($goodsId)
    {
        $groups = GoodsContentGroup::where('goods_id', $goodsId)
            ->order('sort asc, id asc')
            ->select()
            ->map(function ($group) {
                $chapters = GoodsContentChapter::where('group_id', $group->id)
                    ->order('sort asc, id asc')
                    ->field('id,title,sort,is_free,resource_type,create_time')
                    ->select();

                return [
                    'id'       => $group->id,
                    'title'    => $group->title,
                    'sort'     => $group->sort,
                    'is_free'  => $group->is_free,
                    'chapters' => $chapters
                ];
            })->toArray();

        return $groups;
    }
}